package com.yilin.tms.capital.controller;

import com.google.gson.reflect.TypeToken;
import com.yilin.commons.util.JsonUtil;
import com.yilin.commons.util.StringUtil;
import com.yilin.tms.capital.service.ITradeRecordService;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.tms.core.commons.base.BaseController;
import com.yilin.tms.core.commons.base.BaseEntity;
import com.yilin.tms.core.commons.annotation.SkipLoginVerify;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.capital.TradeRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/capital/callback/")
public class CallbackController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(CallbackController.class);

    @Resource
    ITradeRecordService tradeRecordService;


    /**
     * 测试
     */
    @GetMapping(value = "test/{name}/{type}")
    @SkipLoginVerify
    public String test(@PathVariable("name") String name, @PathVariable("type") String userType) {
        logger.info("进来了");
        return "返回成功" + name + userType;
    }

    /**
     * 用于接收第三方交易结果 支付完成回调
     * 银企直连 回调，银企直连前置由我方开发，收到结果时自动调用此接口，分别在即时、3分钟、5分钟、10分钟、30分钟，1小时发送（之后全部间隔一小时），收到SUCCESS为止
     * tradeResults:MapUtil.generate(map1 -> {
     *     map1.put("tradeNo", );
     *     map1.put("tradeStatus", );
     *     map1.put("bankFlowNo", );
     *     map1.put("finishTime", );
     *     map1.put("paymentCapitalAccount", ); 微信支付宝需要填写
     *     map1.put("incomeCapitalAccount", );微信支付宝需要填写
     *     map1.put("tradeFailMsg", ); 银行返回错误信息
     * })
     */
    @PostMapping(value = "bankPayResult")
    @SkipLoginVerify
    public String bankPayResult(String tradeResults, TradeRecord.PayType payType, TradeRecord.BankType bankType) {
        List<TradeRecord> localRecordList = new ArrayList<>();
        List<TradeRecord> tradeResultMapList = JsonUtil.jsonToObject(tradeResults,new TypeToken<List<TradeRecord>>(){});
        for (TradeRecord tradeResult : tradeResultMapList) {
            TradeRecord localRecord = tradeRecordService.getTradeRecordByTradeNo(tradeResult.getTradeNo());
            if (bankType != localRecord.getBankType()) continue;
            if (payType != localRecord.getPayType()) continue;
            localRecord.setTradeStatus(tradeResult.getTradeStatus());
            localRecord.setFinishTime(tradeResult.getFinishTime());
            localRecord.setBankFlowNo(tradeResult.getBankFlowNo());
            if (StringUtil.isNotEmpty(tradeResult.getTradeFailMsg())) localRecord.setTradeFailMsg(tradeResult.getTradeFailMsg());
            if (StringUtil.isNotEmpty(tradeResult.getPaymentCapitalAccount())) localRecord.setPaymentCapitalAccount(tradeResult.getPaymentCapitalAccount());
            if (StringUtil.isNotEmpty(tradeResult.getIncomeCapitalAccount())) localRecord.setIncomeCapitalAccount(tradeResult.getIncomeCapitalAccount());
            localRecord.setBankType(bankType);
            localRecordList.add(localRecord);
        }
        tradeRecordService.updateBatchById(localRecordList);
        //通知支付结果
        List<String> stringList = ArrayUtil.fieldAdd(localRecordList, BaseEntity::getId);
        ParamUtil.isSuccess(tradeRecordService.noticePaymentResult(stringList.toArray(new String[0])));
        return "SUCCESS";
    }
}
